// pages/tool/card/make1/setInfo/setInfo.js
var app = getApp();

//日期选择期开始时间
function dateString(days) {
    var time = new Date().getTime() + 60 * 60 * 1000 * 24 * days;
    return new Date(time).toISOString().split('T')[0];
}

Page({

    /**
     * 页面的初始数据
     */
    data: {
        cardplan: null,
        preview: 0,
        form: [{
            title: "卡券信息",
            fields: [
                {name: "卡券名称", required: true, field: "cy_name", type: "input", datatype: 'text'},
                {
                    name: "卡券型号",
                    required: true,
                    field: "cy_no",
                    suffix: "型",
                    placeholder: "最多4位数字",
                    type: "no",
                    datatype: 'number'
                },
                {name: "兑换有效期", required: true, type: "date", field: "cy_time_expire", format: "yyyy-MM-dd"},
                {name: "兑换须知", field: "exchange_notice", readonly: true, type: "view"},
            ]
        }, {
            title: "企业信息",
            fields: [
                {name: "", field: "logo", tips: "卡券A面左上角显示，凸显企业品牌；默认不显示logo；图片宽度为 400px*200px;透明png格式", type: "pic"},
                {
                    name: "客服电话",
                    required: true,
                    field: "cy_exchange_tel",
                    readonly: "true",
                    placeholder: "请填写客服电话",
                    type: "input",
                    datatype: 'number'
                },
                {
                    name: "服务时间",
                    required: true,
                    field: "service_time",
                    type: "worktime",
                    format: "(工作日{{start}}-{{end}},节假日除外)"
                }
            ]
        }],


        data: {
            brand_id:[],
            logo: '',
            cy_name: '',
            count: 8,
            exchange_notice: "1. 您可在本券（册）{{count}}款商品中任意选择一款您喜欢的礼品进行兑换，提交兑换订单后将免费送货上门；\n" +
                "2.部分商品若因厂家断货或不可抗力造成缺货，我们将以其他等价值商品予以调换；\n" +
                "3.节日兑换高峰期间为确保能及时为您送达，请提前通过微信二维码或网站进行兑换并核对收货信息准确性，以此造成的延误及损失，我司概不负责；\n" +
                "4.本券（册）售出不退还、不记名、不挂失、不找零、不兑换现金。购券（册）时已开具发票，兑换提货时不再提供发票；\n" +
                "5.礼券（册）须在有效期内使用，逾期无法保证指定商品兑换有效性；\n" +
                "6.本礼券（册）法律范围内的最终解释权由发行方{{company}}所有",
            products: [],
            friend_tips: "",
            coupon_id: 3,
            cy_no:'',
            service_time_v:null,
            service_time:null,
            cy_time_expire_v:null,
            cy_exchange_tel:null,
            price_type: 2
        },
        progress: [2, 1, 0, 0,],
        showPage: 1,
        previewTabs: [{title: "快速预览"}, {title: "实时预览"}],
        minprice:0,
        maxprice:-1,
        showtype:[
            {name:'市场价',value:"0"},
            {name:'产品编号',value:"1"},
            {name:'不显示',value:"2"},
        ]
     },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.editcardinfo) {
            if (options.cardplan) {
                this.setData({cardplan: options.cardplan}, () => {
                    this.editcardplan(options.editcardinfo);
                });
            } else {
                this.editcardinfo(options.editcardinfo);
            }
        } else {
            let eventChannel = this.getOpenerEventChannel();
            if (eventChannel != null && eventChannel.on != null) {
                eventChannel.on('definition', (type) => {
                    this.setData({
                        ["data.count"]: type.count,
                        ["data.coupon_id"]: type.templateid,
                        ["data.cy_folds"]: type.folders,
                        ["data.cy_name"]: type.name,
                        ["data.brand_id"]: type.brand_id,
                        definition: type
                    });
                    if (type.count == 1) {
                        this.setData({
                            "exchange_notice": "1.部分商品若因厂家断货或不可抗力造成缺货，我们将以其他等价值商品予以调换；\n" +
                                "2.节日兑换高峰期间为确保能及时为您送达，请提前通过微信二维码或网站进行兑换并核对收货信息准确性，以此造成的延误及损失，我司概不负责；\n" +
                                "3.本券（册）售出不退还、不记名、不挂失、不找零、不兑换现金。购券（册）时已开具发票，兑换提货时不再提供发票；\n" +
                                "4.礼券（册）须在有效期内使用，逾期无法保证指定商品兑换有效性；\n" +
                                "5.本礼券（册）法律范围内的最终解释权由发行方{{company}}所有",
                        })
                    }
                    this.loadTemplate(type.templateid, type.count);
                });
                eventChannel.on('data', (data) => {
                    this.setData({
                        data: data
                    })
                });
                eventChannel.on('nodata', () => {
                    this.loadWithNoData();
                })
            } else {
                this.loadTemplate(this.data.data.coupon_id, this.data.data.count);
                this.loadWithNoData();
            }
        }
    },


    dealDataProducts: function (products, price_type) {
        let result = products;
        for (let i = 0; i < result.length; i++) {
            switch (price_type) {
                case "0":
                    result[i].sprice = "￥" + result[i].sprice1;
                    break;
                case "1":
                    result[i].sprice = "[color=#7f7f7f]编号:" + result[i].id + '[/color]';
                    break;
                default:
                    result[i].sprice = "";
                    break;
            }
        }
        return result;
    },
    selectPriceType : function(e) {
        let price_type = e.currentTarget.dataset.item.value;
        let products = this.dealDataProducts(this.data.data.products,price_type);
        this.setData({
            ["data.price_type"]:price_type,
            ["data.products"]:products,
        },()=>{
            this.emitData();
        });
    },

    //方案编辑
    editcardplan: function (id) {
        app.func.getPromise('/list/plandetail/' + id)
            .then(([code, res]) => {
                let data = res.data.param;
                data['cy_time_expire_v'] = res.data.param['cy_time_expire'];
                this.setData({
                    data: data,
                }, () => {
                    this.loadTemplate(res.data.param.coupon_id, res.data.param.count)
                });
            })
    },

    //编辑
    editcardinfo: function (id) {
        app.func.getPromise('/cardtype/editcardinfo/' + id)
            .then(([code, res]) => {
                this.setData({
                    editId: id,
                    data: res.data,
                }, () => {
                    this.loadTemplate(res.data.coupon_id, res.data.count)
                });
            })
    },

    loadWithNoData: function () {
        //公司信息
        app.func.getPromise("/my/info")
            .then(([code, res]) => {
                this.setData({
                    userid:res.data.userid,
                    ["data.company"]: res.data.customers[0].company,
                    ["data.cy_exchange_tel"]: res.data.customers[0].hotline,
                    ["data.service_time_v"]: res.data.customers[0].service_time || null,
                    ["data.service_time"]: res.data.customers[0].service_name || null,
                }, () => {
                    this.emitData();
                })
            });
        //公章
        app.func.getPromise('/v2/westore/seal/my')
            .then(([code, res]) => {
                if (code == 200) {
                    this.setData({
                        ["data.companyimg"]: res.data
                    }, () => {
                        this.emitData();
                    });
                }
            });
    },

    loadTemplate(id, count) {
        wx.getSystemInfo({
            success: (res) => {
                var width = res.windowWidth;
                var height = res.windowHeight;
                this.setData({
                    designerWidth: width,
                    windowHeight: height
                });
                app.func.getPromise('/v2/coupon/template/' + id + '/' + width + "?count=" + count)
                    .then(([code, res]) => {
                        this.processTemplate(res.data);
                    }).catch(console.error);
            }
        });
    },

    processTemplate(templates) {
        if (templates) {
            let result = [];
            for (let i = 0; i < templates.length; i++) {
                let template = templates[i];
                let areas = JSON.parse(template.template);
                let height = 0;
                for (let i = 0; i < areas.length; i++) {
                    let area = areas[i];
                    area.top = height;
                    height = height + area.height;
                }
                result.push({template: areas, height: height, params: template.params});
            }
            this.setData({
                template: result
            });
        }
    },

    emitData: function () {
        let eventChannel = this.getOpenerEventChannel();
        if (eventChannel != null && eventChannel.emit != null) {
            eventChannel.emit('data', this.data.data);
        }
    },

    onFieldChange: function (e) {
        console.log(e);
        var field = e.currentTarget.dataset.field;
        var value = e.detail.value;
        var _v = e.detail._v;
        this.setData({
            ["data." + field]: value,
            ["data." + field + "_v"]: _v
        }, () => {
            this.emitData();
        });
    },

    addproduct: function () {
        var ids = [];
        if (this.data.data.products != null) {
            for (let i = 0; i < this.data.data.products.length; i++) {
                ids.push(this.data.data.products[i].id);
            }
        }
        let left = this.data.data.count - ids.length;
        console.log(ids);
        var that = this;
        let minprice = this.data.minprice;
        let maxprice = this.data.maxprice;
        let arrayids = ids.join(",");
        let brand_id =  this.data.data.brand_id ? JSON.stringify(this.data.data.brand_id) : false;
        wx.navigateTo({
            url: `/tools/pages/tool/card/make/addproduck/addproduct?id=null&minp=${minprice}&maxp=${maxprice}&maxcount=${left}&ids=${arrayids}&brandid=${brand_id}`,
            events: {
                addProduct: function (e) {
                    let checked = that.dealDataProducts(e.checked,that.data.data.price_type);
                    var products = that.data.data.products;
                    if (products == null) {
                        products = [];
                    }
                    for (let i = 0; i < checked.length; i++) {
                        products.push(checked[i]);
                    }
                    that.setData({
                        ["data.products"]: products,
                        minprice:e.minprice,
                        maxprice:e.maxprice,
                    }, () => {
                        that.emitData();
                    })
                }
            }
        });
    },


    alldelete: function () {
        let that = this;
        isRemoveLogo();
        this.setData({
            ["data.products"]: [],
        }, () => {
            this.emitData();
        });

        function isRemoveLogo() {
            let data = that.data.data.products.filter(ele => ele.brandinfo)
                .map(ele => ele.brandinfo.logo);
            if (data.includes(that.data.logo)) {
                that.setData({
                    ["data.logo"]: '',
                    ["data.isUseBrandlogo"]: false,
                });
            }
        }
    },

    remove: function (e) {
        let that = this;
        let products = this.data.data.products;
        let index = e.currentTarget.dataset.index;
        let item = e.currentTarget.dataset.item;
        products.splice(index, 1);
        item.brandinfo ? isRemoveLogo() : '';
        this.setData({
            ["data.products"]: products
        }, () => {
            this.emitData();
        });


        function isRemoveLogo() {
            let data = products.filter( ele => ele.brandinfo)
                               .map( ele=> ele.brandinfo.logo);
            if(!data.includes(that.data.data.logo)){
                that.setData({
                    ["data.logo"]: '',
                    ["data.isUseBrandlogo"]: false,
                });
            }
        }
    },




    moveup: function (e) {
        var products = this.data.data.products;
        var index1 = e.currentTarget.dataset.index;
        if (index1 > 0) {
            var index2 = index1 - 1;
            var product1 = products[index1];
            var product2 = products[index2];
            this.setData({
                ["data.products[" + index1 + "]"]: product2,
                ["data.products[" + index2 + "]"]: product1
            }, () => {
                this.emitData();
            })
        }
    },

    movedown: function (e) {
        var products = this.data.data.products;
        var index1 = e.currentTarget.dataset.index;
        if (index1 < products.length - 1) {
            var index2 = index1 + 1;

            var product1 = products[index1];
            var product2 = products[index2];
            this.setData({
                ["data.products[" + index1 + "]"]: product2,
                ["data.products[" + index2 + "]"]: product1
            }, () => {
                this.emitData();
            })
        }
    },


    next: function () {
        let data = this.data.data;
        let aitem = [
            {name:'cy_name',          value:data.cy_name,             RegExp:/^\S{2}/,    tips:'卡券名称不能少于两个字'},
            {name:'cy_no',            value:data['cy_no'],            RegExp:/^\S{1,4}$/, tips:'卡券型号不符合规范'},
            {name:'cy_time_expire_v', value:data['cy_time_expire_v'], RegExp:/^\S{5,30}/, tips:'兑换有效期不能为空'},
            {name:'cy_exchange_tel',  value:data['cy_exchange_tel'],  RegExp:/^\S{5,30}/, tips:'客服电话不符合规范'},
            {name:'service_time',     value:data['service_time'],     RegExp:/^\S{5,30}/, tips:'服务时间不能为空'},
        ];
        for(let i=0; i<aitem.length; i++){
            let data = aitem[i];
            let result = data.RegExp.test(data.value);
            if(!result){
                app.func.toastPromise(data.tips);
                return false;
            }
        }
        wx.setNavigationBarTitle({title: '添加商品'});
        this.setData({showPage: 2, progress: [2, 2, 1, 0,]})
    },

    makecard: function () {
        let data = this.data.data;
        let count = this.data.count;
        let cardplan = this.data.cardplan;
        if (!data['products'] || data['products'].length < count) {
            let num = count - data['products'].length;
            app.func.toastPromise('还需要选择' + num + '个商品')
        } else {
            let editId = this.data.editId;
            // console.log(editId);
            if (editId && editId.length > 0) {
                if (cardplan != null) {
                    this.createcard(data);
                } else {
                    this.editcard(data, editId);
                }
            } else {
                this.createcard(data);
            }
        }
    },

    editcard: function (data, id) {
        data['id'] = id;
        app.func.execute(() => {
                return app.func.postPromise('/cardtype/editcard', data).then(([code, res]) => {
                    if (code == 200) {
                        wx.redirectTo({
                            url: '/tools/pages/tool/card/make1/print/print?printid=' + res.data + '&skip=1',
                            success() {
                                return app.func.resolve();
                            }
                        })
                    } else {
                        return app.func.toastPromise(res.message)
                    }
                });
        });
    },

    createcard: function (data) {
        let userid = this.data.userid;
        app.func.execute(()=>{
            return app.func.postPromise('/cardtype/createcard', data).then(([code, res]) => {
                if (code == 200) {
                    wx.reportAnalytics('createcard', {
                        userid: userid,
                    });
                    let eventChannel = this.getOpenerEventChannel();
                    if (eventChannel != null && eventChannel.emit != null) {
                        eventChannel.emit('finish');
                    }
                    wx.redirectTo({
                        url: '/tools/pages/tool/card/make1/print/print?printid=' + res.data + '&skip=1',
                    })
                } else {
                    return app.func.toastPromise(res.message);
                }
            })
        });
    },


    viewFieldInfo: function (e) {
        let name = e.currentTarget.dataset.name;
        let field = e.currentTarget.dataset.field;
        let value = this.data.data[field];
        let text = app.func.render(value, this.data.data);
        wx.navigateTo({
            url: "./textview/textview",
            events: {},
            success: (res) => {
                res.eventChannel.emit('name', name);
                res.eventChannel.emit('text', text);
            }
        })
    },

    preview: function () {
        let id = this.data.data.coupon_id;
        wx.navigateTo({
            url: '../preview/preview?templateid=' + id,
            success: (res) => {
                res.eventChannel.emit('data', this.data.data);
                res.eventChannel.emit('template', this.data.template);
            }
        })
    },

    viewCertificate(e){
        let url = e.currentTarget.dataset.brandinfo.certificate;
        wx.previewImage({
            urls:[url],
        });
    },
    useBrandLogo(e) {
        let logo = e.currentTarget.dataset.brandinfo.logo;
        this.setData({
            ["data.logo"]: logo,
            ["data.isUseBrandlogo"]: true,
        },()=>{
            app.func.toastPromise('设置成功,点击预览，查看效果','none',1500);
        });
    },


    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        let eventChannel = this.getOpenerEventChannel();
        if (eventChannel != null && eventChannel.emit != null) {
            eventChannel.emit('back', {});
        }
    },


});
